<script setup lang="ts">
import { ref } from 'vue';
import axios from 'axios';
import { getCurrentLocation } from '@/service/geolocation';

const coordinates = ref(null);
const loading = ref(false);
const error = ref(null);
const address = ref(
    {
        city: '',
        district: '',
        province:''
    }
);

const getLocation = async () => {
  loading.value = true;
  error.value = null;

  try {
    // 调用获取位置方法
    const position = await getCurrentLocation({
      enableHighAccuracy: true,
      timeout: 10000
    });

    coordinates.value = position;
    console.log('纬度:', position.latitude);
    console.log('经度:', position.longitude);
    const {data}=await axios.get(`/api/user/gaode/coordinate`,{
      params:{
        lat:position.latitude,
        lng:position.longitude
      }
    });
    address.value=data.regeocode.addressComponent;
    console.log(address.value.province,address.value.city,address.value.district);

  } catch (err: any) {
    error.value = err.message;
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <div>
    <button @click="getLocation" :disabled="loading">
      {{ loading ? '定位中...' : '获取位置' }}
    </button>

    <div v-if="coordinates">
      <p>纬度: {{ coordinates.latitude }}</p>
      <p>经度: {{ coordinates.longitude }}</p>
      <p>精度: {{ coordinates.accuracy }}米</p>
      <p>省: {{ address.province }}</p>
      <p>城市: {{ address.city }}</p>
      <p>区: {{ address.district }}</p>
    </div>

    <div v-if="error" class="error">
      {{ error }}
    </div>
  </div>
</template>
